package com.gitee.ywj1352.kaishi.Str;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author wenjie.yang
 * @date 4/28/2020 1:24 PM
 */
public class 无重复字符的最长子串 {

    public static void main(String[] args) {

        System.out.println(optimizationLengthOfLongestSubstring("abba"));


    }


    public static int lengthOfLongestSubstring(String s) {
        int i = 0, j = 0;
        int res = 0;
        char[] chars = s.toCharArray();
        int n = chars.length;
        HashSet<Character> set = new HashSet<>();
        while (i < n && j < n) {
            if (!set.contains(chars[j])) {
                set.add(chars[j]);
                res = Math.max(res, j - i);
                j++;
            } else {
                set.remove(chars[i]);
                i++;
            }
        }
        return res + 1;
    }

    public static int optimizationLengthOfLongestSubstring(String s) {
        int res = 0;
        char[] chars = s.toCharArray();
        int n = chars.length;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            res = Math.max(res, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }

        return res;
    }


}
